﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Read.Application.Commands.Role_command;
using SmartTracking.API.Read.DTO;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.Role_handler
{
    public class GetRoleCommandHandler:IRequestHandler<GetRoleCommand,ApiResult<ApiPaging<RolePermissionDto>>>
    {
        private readonly IBaseRepository<Roles> roleRep;
        private readonly IBaseRepository<RolePermissionsMiddle> rolePermissionRep;
        private readonly IBaseRepository<Permissions> permissionRep;
        private readonly IMapper mapper;

        public GetRoleCommandHandler(
            IBaseRepository<Roles> roleRep,
            IBaseRepository<RolePermissionsMiddle> rolePermissionRep,
            IBaseRepository<Permissions> permissionRep,
            IMapper mapper)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<ApiPaging<RolePermissionDto>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<RolePermissionDto>> result = new ApiResult<ApiPaging<RolePermissionDto>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            var perlist = roleRep.GetAll().Where(x => x.IsDeleted == false);
            var list = mapper.Map<List<RolePermissionDto>>(perlist);

            foreach (var item in list)
            {
                var rolepers = rolePermissionRep.GetAll().Where(x => x.RoleId == item.RoleId).Select(x => x.PermissionId).ToList();
                item.PermissionId = rolepers;
                var permissions = permissionRep.GetAll().Where(x => rolepers.Contains(x.PermissionId)).Select(x => x.PermissionName).ToList();
                item.PermissionName = permissions;
            }
            if(!string.IsNullOrEmpty(request.RoleName))
            {
                list = list.Where(x => x.RoleName == request.RoleName).ToList();
            }

            int ListCount = list.Count();
            int PageCount = (int)Math.Ceiling(ListCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            ApiPaging<RolePermissionDto> paging = new ApiPaging<RolePermissionDto>();
            paging.totalCount = ListCount;
            paging.totalPage = PageCount;
            paging.data = list.ToList();

            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
